package com.jia.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jia.blog.entity.Blog;
import com.jia.blog.entity.User;
import com.jia.blog.mapper.BlogMapper;
import com.jia.blog.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiajia
 * @since 2020-12-02
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {

    @Autowired
    UserService userService;

    @Override
    public Map getList(Integer pageNum, Integer pageSize) {
        Page<Blog> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        IPage<Blog> blogIPage = baseMapper.selectPage(page, wrapper);
        List<Blog> records = blogIPage.getRecords();
        long total = blogIPage.getTotal();
        long size = blogIPage.getSize();
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("size",size);
        map.put("records",records);
        return map;
    }

    @Override
    public List<Blog> getListByCateId(Long cateId) {
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        if(cateId == -1){
            wrapper.eq("recommend",1).orderByDesc("create_time");
        }else{
            wrapper.eq("cate_id",cateId).orderByDesc("create_time");
        }

        List<Blog> collect = baseMapper.selectList(wrapper).stream().map(item -> {
            Long userId = item.getUserId();
            User user = userService.getById(userId);
            String username = user.getUsername();
            String avatar = user.getAvatar();
            item.setUsername(username);
            item.setUserAvatar(avatar);
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Blog> getListByUserId(Long userId) {
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.orderByDesc("create_time");
        List<Blog> blogs = baseMapper.selectList(wrapper);
        return blogs;
    }
}
